import cv2
import os
import shutil
import numpy as np
from PIL import Image

#  加载人脸检测器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')


#  均值哈希算法
def dhash(image):
    #  转为灰度图像
    image = cv2.resize(image,(8,8),interpolation=cv2.INTER_CUBIC)
    #  缩放为更小的尺寸方便计算
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    s = 0
    hash_str = ''
    for i in range(8):
        for j in range(8):
            s= s+gray[i,j]
    avg = s/64
    for i in range(8):
        for j in range(8):
            if gray[i,j] > avg:
                hash_str = hash_str + '1'
            else :
                hash_str = hash_str + '0'
    return hash_str

#  创建保存相似人脸的文件夹
def create_folder(path):
    if not os.path.exists(path):
        os.makedirs(path)


#  加载视频文件
video_path = 'C:/Users/17938/Documents/WXWork/1688853076112674/Cache/File/2023-07/dataset/bili.mp4'
fps = 40
cap = cv2.VideoCapture(video_path)
cap.set(cv2.CAP_PROP_FPS,fps)
#  用于保存当前帧的人脸信息  {哈希值:  [人脸图像,  目标文件夹]}
faces_dict = {}

frame_count = 0
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    #  转换为灰度图像进行人脸检测
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #  人脸检测
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30))

    for (x, y, w, h) in faces:
        #  提取人脸图像
        face_img = frame[y:y + h, x:x + w]

        #  计算图像的哈希值
        hash_value = dhash(face_img)

        #  判断是否有相似人脸已经存在
        folder_path = faces_dict.get(hash_value, '')
        if not folder_path:
            folder_path = os.path.join('D:/1/', str(hash_value))  # 设置保存相似人脸的文件夹路径
            create_folder(folder_path)
            faces_dict[hash_value] = folder_path

        #  将人脸图像保存到对应的文件夹
        face_path = os.path.join(folder_path, 'face{}.jpg'.format(frame_count))
        cv2.imwrite(face_path, face_img)

    frame_count += 1

cap.release()
cv2.destroyAllWindows()